package com.heima.app.filter;

import com.heima.app.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: 全局过滤器 对所有请求拦截
 * @Version: V1.0
 */
@Slf4j
@Component
@Order(1)  // 越小越优先
public class AuthorizeFilter implements GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1 得到当前请求地址，是否是登录
        String url = request.getURI().getPath();
        // 是则放行
        if (url.contains("/login")) {
            return chain.filter(exchange);
        }

        //2 获取前端传递 token
        try {
            String token = request.getHeaders().getFirst("token");
            //2.1 token是否存在并且有效， 无效则拦截
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int verifyToken = AppJwtUtil.verifyToken(claims);
            if (StringUtils.isBlank(token) || verifyToken > 0) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //2.2 token有效， 解析token jwt user id ， 存到 请求 header 中，下发到对应的微服务
            Integer id = claims.get("id", Integer.class);
            ServerHttpRequest httpRequest = request.mutate().headers(header -> {
                /**
                 * 这里是添加请求头
                 * 登录后，生成jwt给用户浏览器，用户访问不同的功能都会携带这个jwt
                 * */
                header.add("userId", id.toString());
            }).build();
            exchange.mutate().request(httpRequest).build();

        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("parse JWT is error：{}", ex);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        return chain.filter(exchange);
    }

}